<?php

namespace App\Http\Middleware\Api\v1;

use App\Models\TimePeriod;
use Illuminate\Support\Carbon;
use Closure;
use App\Exceptions\ApiException;
use App\Exceptions\ApiErrCode;
use App\Services\Utils\ApiChecker;
use Illuminate\Http\Request;
use App\Models\ApiKey;
use App\Models\Customer;
use Illuminate\Support\Facades\Cache;

class JudgeApiKeyRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $apikey = ApiKey::where('key', $request->api_key)
                        ->where('secret', $request->api_secret)
                        ->first();
        if (! $apikey) {
            throw new ApiException(ApiErrCode::API_KEY_ERROR, trans('middleware.api_key.key_or_secret_error'));
        }
        switch ($apikey->status) {
            case 'normal':
                //正常
                break;

            case 'unactive':
                throw new ApiException(ApiErrCode::API_KEY_STATUS_EXCEPTION, trans('middleware.api_key.key_status_exception')); //未激活
                break;

            case 'admin-locked':
                throw new ApiException(ApiErrCode::API_KEY_STATUS_EXCEPTION, trans('middleware.api_key.key_status_exception')); //管理员锁定
                break;

            case 'user-locked':
                throw new ApiException(ApiErrCode::API_KEY_STATUS_EXCEPTION, trans('middleware.api_key.key_status_exception')); //用户锁定
                break;
            
            default:
                # code...
                break;
        }
        // if ($apikey->status != 'normal') {
        //     throw new ApiException(ApiErrCode::API_KEY_STATUS_EXCEPTION, trans('middleware.api_key.key_status_exception'));
        // }
        $customer = Customer::find($apikey->customer_id);
        if ($customer->locked == 1){    //判断用户状态
            throw new ApiException(ApiErrCode::OPERATOR_NOT_ALLOWED, trans('middleware.account_disabled'));
        }
        if (empty($apikey->type) || $apikey->type == 0){    //测试apikey
            if (Cache::has($request->api_key)){
                throw new ApiException(ApiErrCode::API_KEY_CALL_WITHIN_THRESHOLD, trans('middleware.api_key.call_within_threshold'));
            }
        } elseif ($apikey->type == 1){  //按次计费的apikey
            if($customer->amount <= 0){
                throw new ApiException(ApiErrCode::CUSTOMER_AMOUNT_NOT_ENOUGH, trans('middleware.account_amount_not_enough'));
            }
        } elseif ($apikey->type == 2){  //按时间段计费apikey
            $scheme = TimePeriod::where('id', $apikey->type_id)->first();
            if(!Carbon::now()->between($scheme->start_time, $scheme->end_time)){    //apikey是否已激活已过期
                throw new ApiException(ApiErrCode::API_KEY_SCHEME_INVALID, trans('middleware.api_key.key_scheme_invalid'));
            }
        }
        return $next($request);
    }
}
